package org.example.test5.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.test5.service.UserService;
import org.example.test5.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String showIndex() {
        return "index";
    }
    @RequestMapping("/register")
    public String showRegister() {
        return "register";
    }

    @RequestMapping("/login")
    public String showLogin() {
        return "login";
    }

    // 登录请求
    @PostMapping("/login")
    public String login(User user, HttpSession session, Model model) {
        boolean isLoginSuccessful = userService.login(user.getUname(), user.getUpwd());
        if (isLoginSuccessful) {
            session.setAttribute("u", user);  // 登录成功，保存用户信息到 session
            return "redirect:/card/main";  // 登录成功，跳转到主页
        } else {
            model.addAttribute("messageError", "用户名或密码错误");
            return "login";  // 登录失败，返回登录页面
        }
    }

    // 注册请求
    @PostMapping("/register")
    public String register(User user,HttpSession session, Model model) {
        boolean isRegistered = userService.register(user);
        if (isRegistered) {
            session.setAttribute("u", user);  // 注册成功，保存用户信息到 session
            return "redirect:/user/login";  // 跳转到登录页面
        } else {
            model.addAttribute("messageError", "注册失败!用户名已存在!");
            return "register";  // 注册失败，返回注册页面
        }
    }

    //安全退出
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        // 获取当前 session
        HttpSession session = request.getSession(false); // false 表示如果 session 不存在，则返回 null
        if (session != null) {
            // 删除存储在 session 中的用户信息
            session.removeAttribute("u");
            // 或者销毁整个 session
            session.invalidate();
        }
        // 登出后重定向到登录页面
        return "redirect:/user/login";
    }

}